#include "ButtonBeep.h"

#include <QAbstractButton>
#include <QApplication>
#include <QEvent>
#include <QMouseEvent>
#include <QObject>
#include <QTouchEvent>
#include <QWidget>
#include <QtConcurrent>

#ifdef Q_OS_WIN
#include <windows.h>
#endif

// 简单靠谱的按钮滴声事件过滤器
class ButtonBeepEventFilter : public QObject
{
public:
    ButtonBeepEventFilter(QObject* parent = nullptr) : QObject(parent) {}

protected:
    bool eventFilter(QObject* obj, QEvent* event) override
    {
        // 检查被点击的对象是否是按钮
        QAbstractButton* button = qobject_cast<QAbstractButton*>(obj);
        if (button && button->isEnabled()) {
            // 监听鼠标按下事件
            if (event->type() == QEvent::MouseButtonPress) {
                QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
                if (mouseEvent->button() == Qt::LeftButton) {
                    playBeepSound();
                }
            }
            // 监听触摸开始事件
            else if (event->type() == QEvent::TouchBegin) {
                QTouchEvent* touchEvent = static_cast<QTouchEvent*>(event);
                if (!touchEvent->touchPoints().isEmpty()) {
                    playBeepSound();
                }
            }
        }
        return QObject::eventFilter(obj, event);
    }

private:
    static void playBeepSound()
    {
#ifdef Q_OS_WIN
        // 自定义滴声：1000Hz频率，持续80毫秒，清脆的滴声
        QtConcurrent::run([]() { Beep(1000, 80); });
#else
        // Qt跨平台系统声音
        QApplication::beep();
#endif
    }
};

void enableAllButtonBeep()
{
    static ButtonBeepEventFilter* filter = new ButtonBeepEventFilter(qApp);

    // 直接为整个应用程序安装事件过滤器
    // 这样可以捕获所有按钮的点击事件，包括动态创建的
    qApp->installEventFilter(filter);
}